package kr.co.dongpang.android;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sys.app.cms.IdPassword;

public class QRmaker extends Activity {
	ImageView qrImg;
	String copiedStr;
	TextView qrTxt;
	


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qr_maker);
        
        qrImg = (ImageView)findViewById(R.id.qrImg);
        qrTxt = (TextView)findViewById(R.id.qrTxt);

        new qrTask().execute(null, null, null);
    } 
    
    class qrTask extends AsyncTask<Void, Void, Void>{

    	String BASE_QR_URL = "http://chart.apis.google.com/chart?cht=qr&chs=500x500&chld=M&choe=UTF-8&chl=";
    	String fullUrl;
    	
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			
			JSONObject json = JSONfunctions.getJSONfromURL("http://www.dongpang.co.kr/android/dongpang.v01/sm_qrmaker.php?id="+IdPassword.getId(QRmaker.this));

			try {
				JSONArray earthquakes = json.getJSONArray("dongpang");
				JSONObject jobject = earthquakes.getJSONObject(0);

				fullUrl = BASE_QR_URL + jobject.getString("qrcode");
				
				Log.d("","fullUrl:"+fullUrl); 

			} catch (JSONException e) {
				Log.e("log_tag", "Error Parsing data" + e.toString());
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			
			CharSequence clipTxt = " ";
			
	        if((null != clipTxt) && (clipTxt.length() > 0)){
	        	try {
	        		qrTxt.setText(clipTxt);
	        		copiedStr = clipTxt.toString();
					fullUrl += URLEncoder.encode(copiedStr, "UTF-8");
					Picasso.with(QRmaker.this).load(fullUrl).into(qrImg); 
					
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	
	        }else{ //If no text display a dialog.
	        	AlertDialog.Builder builder = new AlertDialog.Builder(QRmaker.this);
	        	
	        	builder.setTitle("QRMaker")
	        	.setCancelable(true)
	        	.setMessage("There was no data in the clipboard! Go copy something and come back")
	        	.setIcon(R.drawable.nuke)
	        	.setNeutralButton("Okay", new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						finish();
						
					}

	        	});
	        	
	        	AlertDialog diag = builder.create();
	        	diag.show();
	        }
			
			
			super.onPostExecute(result);
		}
    	
    }
}
